package com.cloud.common.log.aspect;

import com.cloud.common.core.util.SpringContextUtil;
import com.cloud.common.log.event.SysLogEvent;
import com.cloud.common.log.utils.SysLogUtil;
import com.cloud.api.upms.model.SysLog;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

/**
 * 操作日志使用spring event异步入库
 *
 * @author xn
 */
@Aspect
public class SysLogAspect {

    @SneakyThrows
    @Around("@annotation(sysLog)")
    public Object around(ProceedingJoinPoint point, com.cloud.common.log.annotation.SysLog sysLog) {
        String title=sysLog.title();
        String operateType=sysLog.operate().getCode();

        SysLog log= SysLogUtil.getSysLog();
        log.setTitle(title);
        log.setOperateType(operateType);

        Long startTime=System.currentTimeMillis();
        Object obj;
        try{
            obj = point.proceed();
        }catch(Throwable e){
            log.setException(e.getMessage());
            log.setStatus(0);
            throw e;
        }finally {
            Long endTime = System.currentTimeMillis();
            log.setTime(endTime - startTime);
            SpringContextUtil.publishEvent(new SysLogEvent(log));
        }
        return obj;
    }
}
